package com.scenic.userservice.controller;

import com.github.pagehelper.PageInfo;
import com.scenic.common.bean.Comment;
import com.scenic.common.bean.RespBean;
import com.scenic.common.exception.ScenicSpotException;
import com.scenic.common.service.CommentService;
import com.scenic.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    //添加 -- 评论
    @PostMapping
    public RespBean insert(@RequestBody Comment commentGuide,@RequestHeader("token") String token) throws ScenicSpotException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        commentGuide.setUserId(userId);
        Date date = new Date();
        commentGuide.setUpdateTime(date);
        if (commentService.insert(commentGuide) > 0) {
            return RespBean.ok("评论添加成功");
        }
        return RespBean.error("评论添加失败");
    }

    //根据id删除
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id, @RequestHeader("token") String token) throws ScenicSpotException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        if (!commentService.delete(id, userId)) {
            return RespBean.ok("删除评论失败");
        }

        return RespBean.ok("删除评论成功");
    }
    @GetMapping("/{id}")
    //根据id查询评论
    public RespBean selectById(@PathVariable("id") Integer id) {

        Comment comment = commentService.selectById(id);
        return RespBean.ok("",comment);

    }
    @GetMapping("/user")
    //根据id查询评论
    public RespBean selectByUserId( @RequestHeader("token") String token) {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer)map.get("id");
        Comment condition = new Comment();
        condition.setUserId(userId);
        List<Comment> commentGuides = commentService.selectByCondition(condition);

        return RespBean.ok("",commentGuides);
    }
    //条件分页搜索
    @GetMapping
    public RespBean selectByPage (Comment condition,Integer pageNum, Integer pageSize ) throws ScenicSpotException {
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        PageInfo<Comment> pageInfo = commentService.selectByPage(pageNum, pageSize,condition);

        return RespBean.ok("",pageInfo);
    }
}
